import cv2

def record_video(output_filename, format='avi'):
    # 根据格式选择编码器
    if format.lower() == 'mp4':
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    elif format.lower() == 'avi':
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
    else:
        print("不支持的格式，使用默认的AVI格式")
        fourcc = cv2.VideoWriter_fourcc(*'XVID')

    # 打开摄像头，参数0表示默认摄像头
    cap = cv2.VideoCapture(0)

    # 检查摄像头是否成功打开
    if not cap.isOpened():
        print("无法打开摄像头")
        return

    # 获取视频的宽度和高度
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # 调整后的窗口大小
    new_width = 640
    new_height = 640

    # 创建VideoWriter对象，使用调整后的尺寸
    out = cv2.VideoWriter(output_filename, fourcc, 20.0, (new_width, new_height))

    while True:
        # 读取摄像头帧
        ret, frame = cap.read()

        # 如果帧读取成功
        if ret:
            # 调整帧大小
            frame_resized = cv2.resize(frame, (new_width, new_height))

            # 水平反转帧
            frame_flipped = cv2.flip(frame_resized, 1)

            # 将帧写入文件
            out.write(frame_flipped)

            # 调整窗口大小
            cv2.namedWindow('Recording', cv2.WINDOW_NORMAL)
            cv2.resizeWindow('Recording', new_width, new_height)

            # 显示视频流
            cv2.imshow('Recording', frame_flipped)

            # 按下'q'键退出循环
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break

    # 释放摄像头和VideoWriter资源
    cap.release()
    out.release()

    # 关闭所有OpenCV窗口
    cv2.destroyAllWindows()

# 示例调用
record_video('../video/ok_left.mp4', format='mp4')